package at.fhj.swd.pse.domain;

import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;

import org.jboss.logging.Logger;

import at.fhj.swd.pse.data.CommunityDAO;
import at.fhj.swd.pse.entities.Activity;
import at.fhj.swd.pse.entities.Community;
import at.fhj.swd.pse.entities.EActivityType;
import at.fhj.swd.pse.entities.User;

//import at.fhj.swd.pse.helper.CommunityManager;

@Stateless
public final class CommunityServiceImpl implements CommunityService {
	private final Logger m_logger = Logger.getLogger(CommunityServiceImpl.class);

	// @Inject
	// Use this annotation to determine the type to inject 
	@EJB(beanName="CommunityDAOImpl")
	private CommunityDAO m_dao;

	@Inject
	private ActivityService m_as;

	public CommunityServiceImpl() {
	}

	/**
	 * Used to inject dao and as interface
	 * 
	 * @param dao
	 */
	CommunityServiceImpl(CommunityDAO dao, ActivityService as) {
		m_dao = dao;
		m_as = as;
	}

	@PostConstruct
	public void init() {
		this.m_logger.info("init");
	}

	@Override
	public List<Community> getCommunities() {
		return this.m_dao.getAll();
	}

	@Override
	public Community getCommunity(final int id) {
		return this.m_dao.get(id);
	}

	@Override
	public void addUserToCommunity(final User user, final Community community) {
		this.m_dao.addUserToCommunity(user.getId(), community.getID());

		Activity activity = new Activity();
		activity.setCreator(user);
		activity.setTimestamp(new Date());
		activity.setType(EActivityType.Community);
		activity.setText("joined " + community.getName());
		community.addActivity(activity);
		this.m_as.createNewActivity(activity);
	}

	@Override
	public void releaseCommunity(final Community community) {
		this.m_dao.releaseCommunity(community.getID());
	}

	@Override
	public void createNewCommunity(final Community community) {
		this.m_dao.insert(community);

		Activity activity = new Activity();
		activity.setCreator(community.getAdministractor());
		activity.setTimestamp(new Date());
		activity.setType(EActivityType.Global);
		activity.setText("created " + community.getName());
		community.addActivity(activity);
		this.m_as.createNewActivity(activity);

	}
}
